<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="客户编码" prop="customerId">
        <el-input v-model="queryParams.customerId" placeholder="请输入客户编码" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerNickName">
        <el-input v-model="queryParams.customerNickName" placeholder="请输入客户名称" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户昵称" prop="customerAlias">
        <el-input v-model="queryParams.customerAlias" placeholder="请输入客户昵称" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户权重" prop="customerWeight">
        <el-input v-model="queryParams.customerWeight" placeholder="请输入客户权重" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同签订" prop="contract">
        <el-input v-model="queryParams.contract" placeholder="请输入合同签订" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售" prop="saleName">
        <el-input v-model="queryParams.saleName" placeholder="请输入销售" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客服" prop="customerService">
        <el-input v-model="queryParams.customerService" placeholder="请输入客服" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchReset">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:remove']"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" prop="id" width="250" v-if="false"/>
      <el-table-column label="客户编码" prop="customerId"/>
      <el-table-column label="客户名称" prop="customerNickName"/>
      <el-table-column label="客户昵称" prop="customerAlias"/>
      <el-table-column label="查看合同" align="center" width="260" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            @click="handleViewAttachments(scope.$index, scope.row)"
          >查看合同
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="查看报价" align="center" width="260" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            @click="handleViewQuotation(scope.$index, scope.row)"
          >查看报价
          </el-button>

        </template>
      </el-table-column>
      <el-table-column label="客户权重" prop="customerLevel"/>
      <el-table-column label="系统" prop="erp"/>
      <el-table-column label="合同签订情况" prop="contractSigned"/>
      <el-table-column label="币种" prop="currency"/>
      <el-table-column label="系统固定额度" prop="fixedLimit"/>
      <el-table-column label="结算方式" prop="selttleMethod"/>
      <el-table-column label="付款日期" prop="payDay"/>
      <el-table-column label="中信保审批" prop="approvalBySinosure"/>
      <el-table-column label="中信保额度" prop="sinosureLimit"/>
      <el-table-column label="销售" prop="salesPerson"/>
      <el-table-column label="客服" prop="customerService"/>
    </el-table>
    <!-- 新增合同信息弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
      class="contract-dialog"
      @close="cancel"
    >
      <el-form ref="form" :model="form" class="compact-form">
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户编码" prop="customerId" class="form-item-compact">
              <el-input v-model="form.customerId" placeholder="请输入客户名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerNickName" class="form-item-compact">
              <el-input v-model="form.customerNickName" placeholder="请输入客户名称"/>
            </el-form-item>
          </el-col>


        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户昵称" prop="customerAlias" class="form-item-compact">
              <el-input v-model="form.customerAlias" placeholder="请输入客户昵称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户权重" prop="customerLevel" class="form-item-compact">
              <el-input v-model="form.customerLevel" placeholder="请输入客户权重"/>
            </el-form-item>
          </el-col>

        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="系统" prop="erp" class="form-item-compact">
              <el-input v-model="form.erp" placeholder="请输入系统"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同签订情况" prop="contractSigned" class="form-item-compact">
              <el-input v-model="form.contractSigned" placeholder="请输入合同签订情况"/>
            </el-form-item>
          </el-col>

        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="币种" prop="currency" class="form-item-compact">
              <el-input v-model="form.currency" placeholder="请输入币种"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统固定额度" prop="fixedLimit" class="form-item-compact">
              <el-input v-model="form.fixedLimit" placeholder="请输入系统固定额度"/>
            </el-form-item>
          </el-col>

        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结算方式" prop="selttleMethod" class="form-item-compact">
              <el-input v-model="form.selttleMethod" placeholder="请输入结算方式"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款日期" prop="payDay" class="form-item-compact">
              <el-input v-model="form.payDay" placeholder="请输入付款日期"/>
            </el-form-item>
          </el-col>

        </el-row>

        <!-- 第六行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="中信保审批" prop="approvalBySinosure" class="form-item-compact">
              <el-input v-model="form.approvalBySinosure" placeholder="请输入中信保审批"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="中信保额度" prop="sinosureLimit" class="form-item-compact">
              <el-input v-model="form.sinosureLimit" placeholder="请输入中信保额度"/>
            </el-form-item>
          </el-col>

        </el-row>

        <!-- 第七行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售" prop="salesPerson" class="form-item-compact">
              <el-input v-model="form.salesPerson" placeholder="请输入销售"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客服" prop="customerService" class="form-item-compact">
              <el-input v-model="form.customerService" placeholder="请输入客服"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看合同弹窗 -->
    <el-dialog :title="title" :visible.sync="attachmentWindow" width="600px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="attachments">
              <el-upload
                :action="attachmentUpload.url"
                :headers="attachmentUpload.headers"
                :on-success="handleAttachmentSuccess"
                :before-upload="beforeAttachmentUpload"
                :on-remove="handleRemoveAttachment"
                :limit="5"
                multiple
                list-type="text">
                <el-button type="primary" size="small">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  可上传图片、Excel、PDF、Word文件，单个文件不超过60MB
                </div>
              </el-upload>

              <!-- 文件预览区域 -->
              <div class="file-preview-container">
                <div v-for="(file, index) in attachmentListShow" :key="index" class="file-item">
                  <div @click="handlePreview(file)">
                    <i :class="getFileIcon(file.type)" style="margin-right: 5px;"></i>
                    <span>{{ file.name + '-'+file.date }}</span>
                  </div>
                  <!-- 删除按钮 - 添加权限控制 -->
                  <el-button
                    v-if="hasAdminRole"
                    type="text"
                    size="mini"
                    icon="el-icon-delete"
                    @click="removeFile(file, index)">
                  </el-button>
                </div>
              </div>

            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 图片预览弹窗 -->
      <el-dialog :visible.sync="imagePreviewVisible" append-to-body>
        <img width="100%" :src="previewImageUrl" alt="">
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAttachments">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看报价弹窗 -->
    <el-dialog :title="title" :visible.sync="quotationWindow" width="600px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="attachments">
              <el-upload
                :action="attachmentUpload.url"
                :headers="attachmentUpload.headers"
                :on-success="handleAttachmentSuccessQuotation"
                :before-upload="beforeAttachmentUploadQuotation"
                :on-remove="handleRemoveAttachmentQuotation"
                :limit="5"
                multiple
                list-type="text">
                <el-button type="primary" size="small">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  可上传图片、Excel、PDF、Word文件，单个文件不超过60MB
                </div>
              </el-upload>

              <!-- 文件预览区域 -->
              <div class="file-preview-container">
                <div v-for="(file, index) in quotationListShow" :key="index" class="file-item">
                  <div @click="handlePreview(file)">
                    <i :class="getFileIcon(file.type)" style="margin-right: 5px;"></i>
                    <span>{{ file.name}}</span>
                  </div>
                  <!-- 删除按钮 -->
                  <el-button
                    v-if="hasAdminRole"
                    type="text"
                    size="mini"
                    icon="el-icon-delete"
                    @click="removeQuotationFile(file, index)">
                  </el-button>
                </div>
              </div>

            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormQuotation">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>

</template>

<script>

import { addOrUpdate, deleteByIds, getList } from '@/api/amac/contract/contract'
import { getToken } from '@/utils/auth'
import { getPerformanceAttachments, updateAttachments,
  getPerformanceAttachmentsPrice, updateAttachmentsPrice,} from '@/api/amac/customerContract/customerContract'

export default {
  name: 'Role',
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      pictureDetails: false,  // 控制弹窗显示
      srcList: [],  // 存储图片路径的数组
      currentIndex: 0,  // 当前显示图片的索引
      // 菜单列表
      menuOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerId: undefined,
        customerNickName: undefined,
        customerAlias: undefined,
        customerWeight: undefined,
        contract: undefined,
        saleName: undefined,
        customerService: undefined
      },
      dialogImageUrl: '',
      dialogVisible: false,
      // 图片数量限制
      limit: 3,
      //图片地址
      imageUrl: '',
      // 表单参数
      // 表单参数
      form: {},

      // ... existing data properties ...
      selectedMonth: '', // 当前选择的月份
      submitting: false, // 控制提交按钮的加载状态
      uploadFiles: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/amac/contract/uploadExcel'
      },
      // 新增附件相关数据
      attachmentWindow: false,
      attachmentUpload: {
        headers: {
          Authorization: "Bearer " + getToken()
        },
        url: process.env.VUE_APP_BASE_API + "/amac/departmentMerit/upload/attachment",
      },
      attachmentListShow: [],
      attachmentListPut: [],
      imagePreviewVisible: false,
      previewImageUrl: '',
      currentParentId: null,
      quotationWindow: false,
      quotationListShow: [],
      quotationListPut: [],
      customerIdTemporary:null,
      // 其他数据保持不变
      currentUserRole: '', // 存储当前用户角色

    }
  },
  computed: {
    // 计算属性：检查用户是否为admin
    hasAdminRole() {
      return this.$store.state.user.roles && this.$store.state.user.roles.includes('admin');
    }
  },
  created() {
    this.getList()
    this.getCurrentUserRole(); // 获取当前用户角色
  },
  mounted() {
    // 🔽 页面加载时自动调用
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false
      this.attachmentWindow = false;
      this.quotationWindow = false;
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        customerId: undefined,
        customerNickName: undefined,
        customerAlias:undefined,
        customerLevel: undefined,
        erp: undefined,
        contractSigned: undefined,
        currency: undefined,
        fixedLimit: undefined,
        selttleMethod: undefined,
        payDay: undefined,
        approvalBySinosure: undefined,
        sinosureLimit: undefined,
        salesPerson: undefined,
        customerService: undefined
      }
    },
    //
    // 获取当前用户角色信息
    getCurrentUserRole() {
      const userRoles = this.$store.state.user.roles;
      this.currentUserRole = userRoles;

      // 或者从Vuex获取
      // this.currentUserRole = this.$store.state.user.role;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    searchReset() {
      this.queryParams.pageNum = 1
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        customerId: undefined,
        customerNickName: undefined,
        customerAlias: undefined,
        customerWeight: undefined,
        contract: undefined,
        saleName: undefined,
        customerService: undefined
      }
      this.getList()
    },
    /** 查询列表 */
    getList() {
      getList(this.queryParams).then(response => {
        if (!response.rows) return false
        this.roleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.open = true
      this.title = '新增合同信息'
    },
    handleUpdate() {
      const selected = this.roleList.find(item => item.id === this.ids[0])
      if (!selected) return

      this.form = { ...selected }  // 深拷贝到表单
      this.title = '修改合同信息'
      this.open = true
    },
    handleDelete() {
      this.$confirm('确定要删除选中的数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteByIds(this.ids).then(res => {
          this.$message.success('删除成功')
          this.getList()
        }).catch(() => {
          this.$message.error('删除失败')
        })
      }).catch(() => {
        // 用户点击取消
      })
    },
    /**
     * 新增和修改的确认按钮
     */
    submitForm() {
      this.submitting = true
      console.log('this.form.id', this.form.id)

      addOrUpdate(this.form)  // 不管是新增还是修改，统一走这个方法
        .then(res => {
          this.$message.success(this.form.id ? '修改成功' : '新增成功')
          this.open = false
          this.getList()
        })
        .finally(() => {
          this.submitting = false
        })
    },
    //附件合同
    handleViewAttachments(index, row) {
      this.currentParentId = row.id;
      this.loading = true;
      this.attachmentWindow = true;
      this.title = `查看合同 - ${row.customerNickName}`; // 使用客户名称作为标题
      this.customerIdTemporary=row.customerId
      const queryParams = {
        parentId: row.customerId
      };
      getPerformanceAttachments(queryParams)
        .then(response => {
          if (!response?.data) {
            this.resetAttachmentLists();
            this.$message.info('暂无附件数据');
            return;
          }

          try {
            // 假设后端已直接返回结构化数据，不需要再parse
            const attachmentData = response.data;

            // 处理附件列表
            this.attachmentListShow = this.processAttachmentList(attachmentData);
            this.attachmentListPut = [...this.attachmentListShow];
          } catch (e) {
            console.error('处理附件数据失败:', e);
            this.resetAttachmentLists();
            this.$message.error('附件数据处理失败');
          }
        })
        .catch(error => {
          console.error('获取附件失败:', error);
          this.resetAttachmentLists();
          this.$message.error('获取附件失败: ' + (error.message || '请稍后重试'));
        })
        .finally(() => {
          this.loading = false;
        });
    },

// 辅助方法：处理附件列表
    processAttachmentList(attachmentData) {
      // 如果后端返回的是字符串形式，尝试解析
      const rawList = typeof attachmentData === 'string'
        ? JSON.parse(attachmentData)
        : attachmentData;

      // 确保是数组
      const attachmentList = Array.isArray(rawList) ? rawList : [];
      const formatDate = (date) => {
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        return `${y}-${m}-${d}`;
      };
      return attachmentList.map(item => ({
        url: item.url,
        name: item.name || this.extractFileNameFromUrl(item.url),
        date: formatDate(new Date()),  // ✅ 确保有值
        type: item.type || this.getFileType(item.url)
      }));
    },

// 辅助方法：从URL提取文件名
    extractFileNameFromUrl(url) {
      if (!url) return '未知文件';
      try {
        return url.substring(url.lastIndexOf('/') + 1);
      } catch {
        return '未知文件';
      }
    },

// 辅助方法：重置附件列表
    resetAttachmentLists() {
      this.attachmentListShow = [];
      this.attachmentListPut = [];
    },

    // 获取文件类型
    getFileType(url) {
      const extension = url.split('.').pop().toLowerCase();
      if (['jpg', 'jpeg', 'png', 'gif'].includes(extension)) {
        return 'image';
      } else if (['xls', 'xlsx'].includes(extension)) {
        return 'excel';
      } else if (extension === 'pdf') {
        return 'pdf';
      } else if (['doc', 'docx'].includes(extension)) {
        return 'word';  // 新增word类型
      }
      return 'other';
    },

    // 附件上传前的校验
    beforeAttachmentUpload(file) {
      // const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf',
      //   'application/vnd.ms-excel',
      //   'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
      const allowedTypes = [
        'image/jpeg', 'image/png',
        'application/pdf',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' // Word文档类型
      ];
      const isLt10M = file.size / 1024 / 1024 <60;  // 改为60MB限制

      if (!allowedTypes.includes(file.type)) {
        this.$message.error('只能上传图片、PDF、Word或Excel文件!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传的文件不能超过60MB!');
        return false;
      }

      // // 检查是否已存在同名文件
      // if (this.attachmentListPut.some(item => item.name === file.name)) {
      //   this.$message.error('已存在同名文件!');
      //   return false;
      // }

      return true;
    },

    // 附件上传成功处理
    handleAttachmentSuccess(res, file) {
      const baseUrl = process.env.VUE_APP_BASE_API
      const relativePath = res.data.url
      const fileType = this.getFileType(file.name);
      // 格式化日期函数
      const formatDate = (date) => {
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        return `${y}-${m}-${d}`;
      };
      this.attachmentListPut.push({
        url: baseUrl + relativePath,
        name: file.name,
        date: formatDate(new Date()),
        type: fileType
      });
      this.$message.success('文件上传成功');
    },
    // 删除附件
    handleRemoveAttachment(file, fileList) {
      this.attachmentListPut = this.attachmentListPut.filter(item => item.url !== file.url);
    },
    // 提交附件
    submitFormAttachments() {
      const submitData = {
        date: this.selectedMonth,
        parentId: this.customerIdTemporary,
        attachments: this.attachmentListPut
      };

      this.loading = true;
      updateAttachments(submitData)
        .then(response => {
          this.$message.success('附件保存成功');
          this.attachmentWindow = false;
        })
        .catch(error => {
          console.error('保存附件失败:', error);
          this.$message.error('保存附件失败');
        })
        .finally(() => {
          this.loading = false;
        });

    },
    // 获取文件图标
    getFileIcon(fileType) {
      switch(fileType) {
        case 'image':
          return 'el-icon-picture';
        case 'pdf':
          return 'el-icon-document';
        case 'excel':
          return 'el-icon-document';
        case 'word':
          return 'el-icon-document';  // Word文档图标
        default:
          return 'el-icon-document';
      }
    },

    // 处理预览
    handlePreview(file) {
      if (file.type === 'image') {
        // 图片预览
        this.previewImageUrl = file.url;
        this.imagePreviewVisible = true;
      } else {
        // 其他文件下载
        window.open(file.url, '_blank');
      }
    },
    removeFile(file, index) {
      // 再次检查权限（防止通过其他方式调用）
      if (!this.hasAdminRole) {
        this.$message.warning('您没有权限执行此操作');
        return;
      }
      // 调用已有的删除逻辑
      this.handleRemoveAttachment(file, index);
      // 同时从展示列表移除
      this.attachmentListShow.splice(index, 1);
    },
    //报价附件
    // 查看报价
    handleViewQuotation(index, row) {
      this.currentParentId = row.id;
      this.loading = true;
      this.quotationWindow = true;
      this.title = `查看报价 - ${row.customerNickName}`;
      this.customerIdTemporary=row.customerId
      const queryParams = { parentId: row.customerId };
      getPerformanceAttachmentsPrice(queryParams)
        .then(response => {
          if (!response?.data) {
            this.resetQuotationLists();
            this.$message.info('暂无报价附件');
            return;
          }
          const attachmentData = response.data;
          this.quotationListShow = this.processAttachmentList(attachmentData);
          this.quotationListPut = [...this.quotationListShow];
        })
        .catch(error => {
          console.error('获取报价失败:', error);
          this.resetQuotationLists();
          this.$message.error('获取报价失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },

// 附件上传校验（报价）
    beforeAttachmentUploadQuotation(file) {
      return this.beforeAttachmentUpload(file, this.quotationListPut);
    },

// 附件上传成功（报价）
    handleAttachmentSuccessQuotation(res, file) {
      const baseUrl = process.env.VUE_APP_BASE_API;
      const relativePath = res.data.url;
      const fileType = this.getFileType(file.name);
      const formatDate = (date) => {
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        return `${y}-${m}-${d}`;
      };
      this.quotationListPut.push({
        url: baseUrl + relativePath,
        name: file.name,
        date: formatDate(new Date()),
        type: fileType
      });
      this.$message.success('文件上传成功');
    },

// 删除报价附件
    handleRemoveAttachmentQuotation(file) {
      this.quotationListPut = this.quotationListPut.filter(item => item.url !== file.url);
    },

// 提交报价附件
    submitFormQuotation() {
      const submitData = {
        date: this.selectedMonth,
        parentId: this.customerIdTemporary,
        attachments: this.quotationListPut
      };

      this.loading = true;
      updateAttachmentsPrice(submitData)
        .then(response => {
          this.$message.success('报价附件保存成功');
          this.quotationWindow = false;
        })
        .catch(error => {
          console.error('保存报价失败:', error);
          this.$message.error('保存报价失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },

// 重置报价附件
    resetQuotationLists() {
      this.quotationListShow = [];
      this.quotationListPut = [];
    },
    handleExport(){
      const obj = { ids: this.ids}
      this.download('/amac/contract/export',obj , `合同信息${new Date().getTime()}.xlsx`)
      exportLoading: false
    },
    removeQuotationFile(file, index) {
      // 再次检查权限
      if (!this.hasAdminRole) {
        this.$message.warning('您没有权限执行此操作');
        return;
      }

      // 从展示列表和提交列表中移除文件
      this.quotationListShow.splice(index, 1);
      this.quotationListPut = this.quotationListPut.filter(item => item.url !== file.url);

      this.$message.success('文件删除成功');
    },




  }

}
</script>
<style>
.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 左边文件名，右边按钮 */
  padding: 4px 0;
}
/* 加载提示样式 */
.upload-loading {
  text-align: center;
  padding: 10px 0;
  color: #409EFF;
}

.upload-loading i {
  margin-right: 5px;
  font-size: 16px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 弹窗整体样式 */
.contract-dialog {
  font-family: "Microsoft YaHei", sans-serif;
}

/* 紧凑型表单样式 */
.compact-form {
  padding: 20px 30px;
}

/* 表单项样式 */
.form-item-compact {
  margin-bottom: 18px;
}

.form-item-compact .el-form-item__label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding-right: 12px;
  color: #606266;
  font-weight: normal;
}

.form-item-compact .el-input {
  width: 100%;
  min-width: 180px;
}

/* 底部按钮样式 */
.dialog-footer {
  text-align: center;
  padding: 15px 0 0;
}

.dialog-footer .el-button {
  min-width: 100px;
  margin: 0 10px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .contract-dialog {
    width: 90% !important;
  }

  .form-item-compact .el-input {
    min-width: 150px;
  }
}
</style>
